﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication3
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string checkOnline = Request.QueryString.Get("CheckOnline");
            //如果用户已经检测过是否在线了，并且确认没有登录sso
            if (!string.IsNullOrWhiteSpace(checkOnline) && checkOnline == "true")
            {
                //走正常的登录流程，获取用户提交的用户名和密码之后，调用sso接口去验证
            }
            //调用sso站点的iframe,去验证是否在主站有会话
            else
            {
                string loginUrl = "loginUrl=http://localhost:61756/login";
                string returnUrl = "returnUrl=http://localhost:61756/loginsuccess";
                string iframeUrl = "http://localhost:61659/iframe?";
                string url = string.Format("{0}{1}&{2}", iframeUrl, returnUrl, loginUrl);
                string scriptBlock = string.Format(@"jQuery('#sso').attr('src','{0}')", url);
                string script = "jQuery(function(){" + scriptBlock + "})";
                ClientScript.RegisterStartupScript(this.GetType(), "iframe", script, true);
            }
        }

        protected void login_Click(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:61881/");
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("appliation/json"));
            UserInfo user = new UserInfo()
            {
                AppKey = "aaa",
                AppSecret = "sss",
                UserName = "km",
                Password = "0000",
                Ip = "127.0.0.1",
            };
            HttpResponseMessage response = client.PostAsJsonAsync("api/sso/login", user).Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsAsync<Result>().Result;
                Response.Redirect("http://localhost:61756/loginsuccess.aspx" + $"?token={result.Data?.Token}&user={result.Data?.UserName}");
            }
        }
    }
}